package com.song.controller.role;

import com.song.common.Result;
import com.song.controller.BaseController;
import com.song.entity.role.UserRole;
import com.song.service.role.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;


/**
 * 用户所属角色
 */
@Controller
@RequestMapping("${api.version}/userRole")
public class UserRoleController extends BaseController {

    @Autowired
    private UserRoleService userRoleService ;

    /**
     * 新增用户所属角色
     */
    @RequestMapping("/addUserRoles")
    @ResponseBody
    public Result addUserRoles(Integer userId, String roleIds) {
        String[] ids = roleIds.split(",");
        // 先删除
        boolean bool = userRoleService.deleteById(userId);
        if (!bool) {
            return error("删除用户对应的角色列表失败！");
        }
        List<UserRole> list = new ArrayList<>();
        // 至少有一条数据
        if(!ids[0].equals("")) {
            for (String roleId : ids) {
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(Integer.valueOf(roleId));
                list.add(userRole);
            }
            userRoleService.batAddUserRole(list);
        }
        return success();
    }
}
